import 'dart:async';
import 'package:flutter/material.dart';

/// 倒计时控件
class CountdownButton extends StatefulWidget {
  /// 倒计时时长,默认30秒
  final int seconds;
  final Future<bool> Function()? onPressed;

  /// 倒计时结束后执行
  final VoidCallback? onCountdownFinishCallBack;

  CountdownButton({
    Key? key,
    this.seconds = 30,
    this.onPressed,
    this.onCountdownFinishCallBack,
  }) : super(key: key);

  @override
  createState() => _CountdownButtonState();
}

class _CountdownButtonState extends State<CountdownButton> {
  var _seconds;
  Timer? _timer;

  /// 是否可点击
  bool _isClick = true;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
      style: ButtonStyle(
        padding: WidgetStateProperty.all<EdgeInsetsGeometry>(
          const EdgeInsetsDirectional.only(start: 8.0, end: 8.0),
        ),
        // textStyle: MaterialStateProperty.all(TextStyle(color: Color(0xFF5BC0DE))),
        textStyle:
            WidgetStateProperty.resolveWith((Set<WidgetState> states) {
          if (states.contains(WidgetState.pressed))
            return TextStyle(color: Color(0xFF5BC0DE));
          if (states.contains(WidgetState.disabled))
            return TextStyle(color: Colors.white);
          return null;
        }),
        backgroundColor: WidgetStateProperty.resolveWith((states) {
          if (states.contains(WidgetState.pressed)) return Colors.transparent;
          if (states.contains(WidgetState.disabled)) return Color(0xFFCCCCCC);
          return null;
        }),
        shape: WidgetStateProperty.all<OutlinedBorder>(
          RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25.0),
            side: BorderSide(
              color: _isClick ? Color(0xFF5BC0DE) : Color(0xFFCCCCCC),
              width: 0.8,
            ),
          ),
        ),
        side: WidgetStateProperty.resolveWith<BorderSide>(
            (Set<WidgetState> states) {
          final Color color =
              states.contains(WidgetState.pressed) ? Colors.blue : Colors.red;
          return BorderSide(color: color, width: 2);
        }),
      ),
      child: Text(
        _isClick ? "发送验证码" : "$_seconds 秒后重试",
        style: TextStyle(fontSize: 12),
      ),
      onPressed: _isClick ? _startTimer : null,
    );
  }

  /// 启动倒计时的计时器。
  void _startTimer() async {
    if (widget.onPressed != null) {
      if (!await widget.onPressed!()) {
        return;
      }
    }
    setState(() {
      _seconds = widget.seconds;
      _isClick = false;
    });
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_seconds <= 1) {
          _isClick = true;
          _cancelTimer();
          if (widget.onCountdownFinishCallBack != null) {
            widget.onCountdownFinishCallBack!();
          }
        }
      });
      _seconds--;
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }
}
